package cn.jtool.dig.client.comm.tunnel.protocol;

import cn.jtool.dig.client.comm.VirtualManager;
import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.SNGenerator;
import cn.jtool.dig.common.netty.TcpClient;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class P_14_CloseSession implements ProtocolProcess {

    @Override
    public int protocolId() {
        return Commands.CLOSE_SESSION.getCode();
    }
    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        PacketHeader header = packet.getHeader();
        Long channelId = header.getChannelId();

        TcpClient client = VirtualManager.getClient(channelId);
        if(Objects.nonNull(client)){
            client.stop();
            VirtualManager.removeClient(header.getChannelId());
        }

        PacketHeader outheader = new PacketHeader();
        outheader.setCommand(Commands.COMMON_RESPONSE.getCode());
        outheader.setSn(SNGenerator.gen());
        outheader.setDigId(0x00);
        outheader.setChannelId(channelId);
        PacketBody outbody = new PacketBody();
        outbody.writeByte(this.protocolId());
        outbody.writeWord(header.getSn());
        outbody.writeByte(0x00);
        return Packet.builder().header(outheader).body(outbody).build();
    }
}
